﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace Solidi
{
	public class DependencyChildLifetime : DependencyContextDecorator, IDependencyLifetime
	{
		private ConcurrentStack<DependencyChild> _children = new ConcurrentStack<DependencyChild>();

		public DependencyChildLifetime(IDependencyContext context)
			: base(context)
		{
			
		}

		public void ReleaseChildren()
		{
			foreach (DependencyChild child in _children)
			{
				child.Release();
			}
		}

		public override IDependencyLifetime Lifetime
		{
			get
			{
				return this;
			}
		}

		public bool Release(object instance)
		{
			return Resolver.Release(this, instance);
		}

		public object Resolve(IDependencyContext context, IDependency dependency)
		{
			IDependencyReference reference = dependency.Resolve(context);

			if (reference != null)
			{
				object instance = reference.Value;

				DependencyChild resolution = new DependencyChild(dependency, reference);

				_children.Push(resolution);

				return instance;
			}

			return null;
		}
	}
}
